<template>
  <div class="ai-message-component">
    <div v-if="formatted" class="formatted-content" ref="contentRef" v-html="cleanFormattedContent"></div>
    <div v-else class="plain-content">{{ content }}</div>
  </div>
</template>

<script setup>
import {ref, watch, computed, onMounted, onBeforeUnmount} from 'vue';
import {formatAIResponse, containsCodeBlock, containsTable} from '../utils/formatter';
import {safeClipboardWrite} from '../utils/browser';

const props = defineProps({
  content: {
    type: String,
    required: true
  },
  useMarkdown: {
    type: Boolean,
    default: true
  }
});

// 状态变量
const formatted = ref('');
const contentRef = ref(null);
const hasCode = ref(false);
const hasTable = ref(false);

// 配置参数
const CONFIG = {
  COPY_TIMEOUT: 1000,     // 复制按钮文本恢复延时(毫秒)
  COPY_SUCCESS_TEXT: '已复制!',
  COPY_FAILURE_TEXT: '复制失败',
  DECODE_ERROR_TEXT: '解码失败'
};

// 清理内容，处理[object Object]和undefined
const cleanFormattedContent = computed(() => {
  if (!formatted.value) return '';
  return formatted.value;
});

// 格式化内容
const formatContent = () => {
  try {
    // 清空状态用于重置
    formatted.value = '';
    hasCode.value = false;
    hasTable.value = false;

    // 验证内容类型
    if (props.content === null || props.content === undefined) {
      return;
    }

    const contentStr = typeof props.content === 'string'
        ? props.content
        : String(props.content || '');

    // 检测内容特性
    hasCode.value = containsCodeBlock(contentStr);
    hasTable.value = containsTable(contentStr);

    // 应用格式化
    formatted.value = props.useMarkdown
        ? formatAIResponse(contentStr)
        : contentStr;

  } catch (err) {
    // 出错时使用简单文本显示
    const errorContent = typeof props.content === 'object'
        ? JSON.stringify(props.content, null, 2)
        : String(props.content || '');

    formatted.value = `<pre>${errorContent}</pre>`;
  }
};

// 复制按钮点击处理
const handleCopyButtonClick = (event) => {
  // 检查点击的是否是复制按钮
  if (!event.target?.classList.contains('copy-button')) return;

  const button = event.target;
  const codeData = button.getAttribute('data-code');
  if (!codeData) return;

  const originalText = button.textContent;

  try {
    const decodedCode = decodeURIComponent(codeData);

    // 执行复制操作
    safeClipboardWrite(decodedCode)
        .then(success => {
          updateCopyButtonState(
              button,
              success ? CONFIG.COPY_SUCCESS_TEXT : CONFIG.COPY_FAILURE_TEXT,
              originalText
          );
        })
        .catch(() => {
          updateCopyButtonState(button, CONFIG.COPY_FAILURE_TEXT, originalText);
        });
  } catch (err) {
    updateCopyButtonState(button, CONFIG.DECODE_ERROR_TEXT, '复制');
  }
};

// 更新复制按钮状态
const updateCopyButtonState = (button, tempText, originalText) => {
  button.textContent = tempText;
  button.disabled = true;

  setTimeout(() => {
    button.textContent = originalText;
    button.disabled = false;
  }, CONFIG.COPY_TIMEOUT);
};

// 设置复制按钮事件监听
const setupCopyButtons = () => {
  if (!contentRef.value) return;

  // 添加事件监听
  contentRef.value.addEventListener('click', handleCopyButtonClick);
};

// 移除事件监听
const cleanupEventListeners = () => {
  if (contentRef.value) {
    contentRef.value.removeEventListener('click', handleCopyButtonClick);
  }
};

// 监听内容变化
watch(() => props.content, () => {
  formatContent();
  // 等待DOM更新后再设置事件监听
  setTimeout(setupCopyButtons, 100);
}, {immediate: true});

// 组件挂载时执行
onMounted(() => {
  setupCopyButtons();
});

// 组件销毁前清理
onBeforeUnmount(() => {
  cleanupEventListeners();
});
</script>

<style scoped>
/* 基础样式 */
.ai-message-component {
  width: 100%;
  box-sizing: border-box;
  overflow-x: auto;
}

.formatted-content {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
  line-height: 1.6;
  text-align: left;
  width: 100%;
  box-sizing: border-box;
}

/* 代码样式 */
.formatted-content :deep(code) {
  font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
  background-color: rgba(0, 0, 0, 0.04);
  padding: 2px 4px;
  border-radius: 3px;
  font-size: 0.9em;
  tab-size: 4;
}

/* 增强的代码块容器 */
.formatted-content :deep(.code-block-container) {
  margin: 1em auto;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid #ddd;
  background-color: #f6f8fa;
  width: 100%;
  box-sizing: border-box;
  max-width: 100%;
  display: block;
}

.formatted-content :deep(.code-header) {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f1f1f1;
  padding: 8px 12px;
  border-bottom: 1px solid #ddd;
  position: sticky;
  left: 0;
  top: 0;
  z-index: 10;
}

.formatted-content :deep(.copy-button) {
  background-color: #e9e9e9;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 3px 8px;
  font-size: 0.8em;
  cursor: pointer;
  transition: all 0.2s;
}

.formatted-content :deep(.copy-button:hover) {
  background-color: #d5d5d5;
}

.formatted-content :deep(.copy-button:disabled) {
  background-color: #8bc34a;
  color: white;
  cursor: default;
}

.formatted-content :deep(pre) {
  background-color: #f6f8fa;
  border-radius: 0;
  padding: 0;
  overflow: auto;
  margin: 0;
  white-space: pre;
  tab-size: 4;
  width: 100%;
}

.formatted-content :deep(pre code) {
  background-color: transparent;
  padding: 1em;
  white-space: pre;
  tab-size: 4;
  width: max-content; /* 允许内容决定宽度 */
  min-width: 100%; /* 至少与容器一样宽 */
  font-size: 16px;
  font-family: 'Consolas', 'Monaco', 'Andale Mono', monospace;
  line-height: 1.5;
  display: block;
}

.formatted-content :deep(.hljs) {
  padding: 12px 16px;
  margin: 0;
  box-sizing: border-box;
}

/* 标题样式 */
.formatted-content :deep(h1),
.formatted-content :deep(h2),
.formatted-content :deep(h3),
.formatted-content :deep(h4),
.formatted-content :deep(h5),
.formatted-content :deep(h6) {
  margin-top: 24px;
  margin-bottom: 16px;
  font-weight: 600;
  line-height: 1.25;
}

.formatted-content :deep(h1) {
  font-size: 1.8em;
  border-bottom: 1px solid #eee;
  padding-bottom: 0.3em;
}

.formatted-content :deep(h2) {
  font-size: 1.5em;
  border-bottom: 1px solid #eee;
  padding-bottom: 0.3em;
}

.formatted-content :deep(h3) {
  font-size: 1.25em;
}

.formatted-content :deep(h4) {
  font-size: 1em;
}

/* 段落和列表 */
.formatted-content :deep(p) {
  margin: 0.8em 0;
}

.formatted-content :deep(ul),
.formatted-content :deep(ol) {
  padding-left: 2em;
  margin: 0.8em 0;
}

/* 引用块 */
.formatted-content :deep(blockquote) {
  padding: 0 1em;
  color: #6a737d;
  border-left: 0.25em solid #dfe2e5;
  margin: 0.8em 0;
}

/* 表格样式 */
:deep(.table-container) {
  overflow-x: auto !important;
  margin: 1em 0 !important;
  max-width: 100% !important;
  display: block !important;
  border: 1px solid #ddd !important;
  border-radius: 6px !important;
  width: 99% !important;
}

:deep(.formatted-table),
:deep(table) {
  width: 100% !important;
  border-collapse: collapse !important;
  border-spacing: 0 !important;
  margin: 0 !important;
  background-color: white !important;
}

:deep(.formatted-table th),
:deep(.formatted-table td),
:deep(table th),
:deep(table td) {
  border: 1px solid #ddd !important;
  padding: 8px !important;
  text-align: left !important;
  min-width: 60px !important;
  max-width: 300px !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  white-space: normal !important;
  word-break: break-word !important;
}

:deep(.formatted-table th),
:deep(table th) {
  background-color: #f5f5f5 !important;
  font-weight: bold !important;
  position: sticky !important;
  top: 0 !important;
  z-index: 1 !important;
}

:deep(.formatted-table tr:nth-child(even)),
:deep(table tr:nth-child(even)) {
  background-color: #f9f9f9 !important;
}

/* 行内数学公式 */
.formatted-content :deep(.math-inline) {
  padding: 0 3px;
  background-color: #f9f9f9;
  border-radius: 3px;
  font-style: italic;
}

/* 块级数学公式 */
.formatted-content :deep(.math-block) {
  display: block;
  margin: 1em 0;
  padding: 1em;
  background-color: #f9f9f9;
  border-left: 3px solid #dfe2e5;
  overflow-x: auto;
  font-style: italic;
}

/* 纯文本样式 */
.plain-content {
  white-space: pre-wrap;
  word-break: break-word;
  text-align: left;
}

/* 强调内容 */
.formatted-content :deep(strong) {
  font-weight: 600;
}

.formatted-content :deep(em) {
  font-style: italic;
}

/* 链接样式 */
.formatted-content :deep(a) {
  color: #0366d6;
  text-decoration: none;
}

.formatted-content :deep(a:hover) {
  text-decoration: underline;
}

/* 图片样式 */
.formatted-content :deep(img) {
  max-width: 100%;
  height: auto;
  margin: 1em 0;
  border-radius: 5px;
}

/* 分割线 */
.formatted-content :deep(hr) {
  height: 1px;
  background-color: #eaecef;
  border: none;
  margin: 1.5em 0;
}

/* 大型代码块的特殊样式 */
.formatted-content :deep(.large-code-block) {
  position: relative;
}

.formatted-content :deep(.large-code-block .code-size) {
  font-size: 0.75em;
  color: #e91e63;
  margin-right: 8px;
}

.formatted-content :deep(.large-code-block pre) {
  max-height: 400px;
}
</style>